package com.cloudpark.mqtt;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;

/**
 * MQTT Publisher
 * 
 * @author huixiao200068
 *
 */

public class MQTTPub {

    public static void main(String[] args) throws Exception {
        try {

            MqttClient client = new MqttClient(Configuration.TCPAddress, "publisher");

            client.connect();

            MqttTopic topic = client.getTopic(Configuration.topic);

            BufferedReader br = null;
            new BufferedReader(new InputStreamReader(System.in));
            String message = "You don't publish any message!";
            while (true) {
                System.out.print("请输入待发布信息：");
                br = new BufferedReader(new InputStreamReader(System.in));
                String m = br.readLine();
                if (m != null && !m.trim().equals("")) {
                    message = m;
                }

                MqttMessage _m = new MqttMessage(message.getBytes("utf8"));
                _m.setQos(Configuration.QoS);

                MqttDeliveryToken token = topic.publish(_m);
                token.waitForCompletion(Configuration.sleepTimeout);

                System.out.println("Delivery token " + token.hashCode() + " has been received : " + token.isComplete());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
